<template>
  <div>
    <el-container>
      <el-main>
        <el-form :inline="true">
          <el-form-item v-if="!ifSelectChildren" style="height: 18px">
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="uploadFile"
              :before-upload="beforeUpload"
              :show-file-list="false"
            >
              <el-button type="primary">批量导入</el-button>
            </el-upload>
          </el-form-item>
          <!--          <el-form-item v-if="!ifSelectChildren" style="height: 18px">-->
          <!--            <el-button type="primary">单个添加</el-button>-->
          <!--          </el-form-item>-->
          <el-form-item v-if="!ifSelectChildren" style="height: 18px">
            <el-button type="primary" @click="selectFunction">选择加入行政班</el-button>
          </el-form-item>
          <el-link v-if="!ifSelectChildren" :href="baseUrl+studentURL" style="margin-left: 20px">
            <el-button type="text" icon="el-icon-download" style="font-weight: bold">Excel模板下载</el-button>
          </el-link>
          <el-button v-if="ifSelectChildren" type="info" @click="selectCancelFunction()">取消</el-button>
          <el-input v-if="ifSelectChildren" v-model="inputGrade" placeholder="请输入年级" style="width: 150px;" />
          <el-button v-if="ifSelectChildren" icon="el-icon-search" @click="showOnly">未加入行政班</el-button>
          <el-button v-if="ifSelectChildren&&ifShowAll" type="text" @click="getSList">显示全部</el-button>
          <el-button v-if="ifSelectChildrenData" type="warning" @click="showAddToClassDialog">添加至行政班</el-button>
        </el-form>
        <el-divider />
        <el-card class="box-card">
          <el-table ref="multipleTable" :data="tableData" style="width: 100%" size="small" stripe border row-key="studentId" @selection-change="handleSelectionChange">
            <el-table-column
              v-if="ifSelectChildren"
              type="selection"
              width="55"
              :reserve-selection="true"
            />
            <el-table-column prop="studentId" label="学号" style="width: 10%">
              <template slot-scope="scope">
                {{ scope.row.studentId ? scope.row.studentId :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="childName" label="姓名" style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.childName ? scope.row.childName :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" style="width: 6%" align="center">
              <template slot-scope="scope">
                {{ scope.row.gender ? scope.row.gender :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="entryGrade" label="入学年级" style="width: 6%" align="center">
              <template slot-scope="scope">
                {{ scope.row.entryGrade ? scope.row.entryGrade :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="entryYear" label="入学年份" style="width: 6%" align="center">
              <template slot-scope="scope">
                {{ scope.row.entryYear ? scope.row.entryYear :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="className" label="幼儿班级" style="width: 10%" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.className">  {{ scope.row.className ? scope.row.className :'暂无' }}</el-tag>
                <el-tag v-if="!scope.row.className" type="info"> 暂无</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="parentName" label="家长姓名" style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.parentName ? scope.row.parentName :'暂无' }}
              </template>
            </el-table-column>
            <el-table-column prop="parentPhoneNumber" label="家长电话" style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.parentPhoneNumber ? scope.row.parentPhoneNumber :'暂无' }}
              </template>
            </el-table-column>
            <!--            <el-table-column fixed="right" label="操作" style="width: 20%" align="center">-->
            <!--              <template slot-scope="scope">-->
            <!--                  <el-button type="primary" icon="el-icon-edit" @click="handleClick(scope.$index)" />-->
            <!--                <el-button size="small" type="primary" @click="handleClick(scope.$index)">编辑</el-button>-->
            <!--                <el-button type="primary" size="small" icon="el-icon-edit" @click="handleClick(scope.$index)" />-->
            <!--                <template>-->
            <!--                  <el-popconfirm title="确定要删除该学生吗？">-->
            <!--                    &lt;!&ndash;                      <el-button slot="reference" type="primary" icon="el-icon-delete" @click="handleClickDelete(scope.$index)" />&ndash;&gt;-->
            <!--                    <el-button slot="reference" size="small" type="danger" icon="el-icon-delete" />-->
            <!--                  </el-popconfirm>-->
            <!--                </template>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
          <el-pagination
            v-if="ifShowOnly"
            :current-page="page.pageNum"
            :total="page.totalSize"
            style="margin-top: 10px;float: right;margin-bottom: 10px"
            layout="total,prev, pager, next, jumper"
            @current-change="handleCurrentChange"
          />
          <el-pagination
            v-if="!ifShowOnly"
            :current-page="pageOnly.pageNumOnly"
            :total="pageOnly.totalSizeOnly"
            style="margin-top: 10px;float: right;margin-bottom: 10px"
            layout="total,prev, pager, next, jumper"
            @current-change="handleCurrentChangeOnly"
          />
        </el-card>
        <el-dialog title="添加至行政班" :visible.sync="ifShowAddToClassDialog">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
            <el-form-item label="行政班" prop="classId">
              <el-select
                v-model="ruleForm.classId"
                filterable
                remote
                clearable="true"
                placeholder="请选择行政班级"
              >
                <el-option v-for="item in classOptions" :key="item.cid" :label="item.className" :value="item.cid" />
                <div style="bottom: 0;width: 100%;background: #fff">
                  <el-pagination
                    small
                    :current-page="pageSecond.pageNumSecond"
                    :total="pageSecond.totalSizeSecond"
                    layout="prev, pager,next,total"
                    @current-change="handleCurrentChangeSecond"
                  />
                </div>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm()">确定</el-button>
              <el-button @click="ifShowAddToClassDialog = false;resetForm('ruleForm')">取 消</el-button>
            </el-form-item>
          </el-form>

        </el-dialog>
      </el-main>
    </el-container>

  </div>
</template>

<script>
import { uploadStudentExcel } from '../../../api/user'
import { getStu_noClass, getStudentList, setStuToClass } from '../../../api/student'
import { getClass } from '../../../api/class'

export default {
  name: 'Children',
  data() {
    return {
      baseUrl: this.global.picBaseUrl,
      flag: false, // 判断是分页调用还是搜索调用
      inputGrade: '',
      pageSecond: {
        pageNumSecond: 1,
        pageSizeSecond: 10,
        totalPageSecond: 0,
        totalSizeSecond: 0
      },
      classOptions: [],
      ruleForm: {
        classId: ''
      },
      rules: {
        classId: [
          { required: true, message: '请选择行政班级', trigger: 'blur' }
        ]
      },
      ifShowAddToClassDialog: false,
      sidSelectionString: '',
      sidsSelection: [],
      multipleSelection: [],
      ifSelectChildrenData: false,
      ifSelectChildren: false,
      ifShowOnly: true,
      ifShowAll: false,
      page: {
        pageNum: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      pageOnly: {
        pageNumOnly: 1,
        pageSizeOnly: 10,
        totalPageOnly: 0,
        totalSizeOnly: 0
      },
      url: this.baseUrl + '/file/excel?type=student',
      studentURL:'/file/excel?type=student',
      tableData: [],
      List: []
    }
  },
  created() {
    this.getSList()
  },
  methods: {
    // 提交划分行政班表单
    submitForm() {
      this.sidsSelection = []
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log(this.ruleForm.classId)
          console.log(this.multipleSelection)
          for (var i = 0; i < this.multipleSelection.length; i++) {
            this.sidsSelection[i] = this.multipleSelection[i].sid
            // this.sidsSelection.push({ sids: this.multipleSelection[i].sid })
          }console.log(this.sidsSelection)
          //  设置行政班
          setStuToClass({
            cid: this.ruleForm.classId,
            sids: this.sidsSelection
          }).then(res => {
            this.ifShowAddToClassDialog = false
            this.$message.success('设置行政班成功！')
            this.$refs.multipleTable.clearSelection()
            this.getSList()
          })
        } else {
          alert('填写不符合要求')
          return false
        }
      })
    },
    // 显示对话框
    showAddToClassDialog() {
      this.ifShowAddToClassDialog = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.ifSelectChildrenData = true
      } else {
        this.ifSelectChildrenData = false
      }
      console.log(this.multipleSelection)
    },
    handleCurrentChangeSecond(val) {
      this.pageSecond.pageNumSecond = val
      this.getAllAdministrativeClass()
    },
    // 获取行政班列表
    getAllAdministrativeClass() {
      getClass({
        classType: '0',
        pageNum: this.pageSecond.pageNumSecond,
        pageSize: this.pageSecond.pageSizeSecond
      }).then(res => {
        this.classOptions = res.data.list
        this.pageSecond.pageNumSecond = res.data.page.pageNum
        this.pageSecond.pageSizeSecond = res.data.page.pageSize
        this.pageSecond.totalPageSecond = res.data.page.totalPage
        this.pageSecond.totalSizeSecond = res.data.page.totalSize
      })
    },
    selectFunction() {
      this.ifSelectChildren = true // 多选框显示
      this.page.pageNum = 1
      this.page.pageSize = 10
      this.getSList()
      this.getAllAdministrativeClass()
    },
    selectCancelFunction(rows) {
      this.ifSelectChildren = false // 取消多选
      this.page.pageNum = 1
      this.page.pageSize = 10
      this.getSList()
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getSList()
    },
    handleCurrentChangeOnly(val) {
      this.pageOnly.pageNumOnly = val
      this.flag = true
      this.showOnly()
    },
    getSList() {
      if (this.ifShowAll === true) {
        this.inputGrade = ''
        this.ifShowOnly = true
        this.ifShowAll = false
        this.$refs.multipleTable.clearSelection()
      }
      getStudentList({
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      }).then(async res => {
        // this.tableData = res.data.list
        this.List = res.data.list
        this.page = res.data.page
        console.log(res.data.list.length)
        // 根据cid获取班级名称
        for (var i = 0; i < res.data.list.length; i++) {
          var id = this.List[i].cid
          await getClass({ cid: id })
            .then(res => {
              console.log(res.data.list[0].className)
              if (id) {
                this.List[i].className = res.data.list[0].className
              } else {
                this.List[i].className = null
              }
              console.log(this.List)
            }).catch(err => {
            })
        }
        this.tableData = this.List
      }).catch(err => {
      })
    },
    // 获取未加入行政班的学生
    showOnly() {
      if (this.flag = false || this.ifShowAll === false) {
        this.$refs.multipleTable.clearSelection()
      }
      this.flag = false
      if (!this.inputGrade) {
        alert('请先输入年级！')
      }
      getStu_noClass({
        grade: this.inputGrade,
        pageNum: this.pageOnly.pageNumOnly,
        pageSize: this.pageOnly.pageSizeOnly
      }).then(async res => {
        // this.tableData = res.data.list
        this.ifShowOnly = false
        this.ifShowAll = true
        this.List = res.data.list
        this.pageOnly.pageNumOnly = res.data.page.pageNum
        this.pageOnly.pageSizeOnly = res.data.page.pageSize
        this.pageOnly.totalPageOnly = res.data.page.totalPage
        this.pageOnly.totalSizeOnly = res.data.page.totalSize
        console.log(this.pageOnly)
        console.log(res.data.list.length)
        // 根据cid获取班级名称
        for (var i = 0; i < res.data.list.length; i++) {
          var id = this.List[i].cid
          await getClass({ cid: id })
            .then(res => {
              console.log(res.data.list[0].className)
              if (id) {
                this.List[i].className = res.data.list[0].className
              } else {
                this.List[i].className = null
              }
              console.log(this.List)
            }).catch(err => {
            })
        }
        this.tableData = this.List
      }).catch(err => {
      })
    },
    beforeUpload(file) {
      console.log(file)
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls'
      const extension2 = testmsg === 'xlsx'
      if (!extension && !extension2) {
        this.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning' })
      }
      return extension || extension2
    },
    uploadFile(item) {
      var that = this
      const fileObj = item.file
      // FormData 对象
      const form = new FormData()
      // 文件对象
      form.append('file', fileObj)
      uploadStudentExcel(form).then(res => {
        this.url = res.data
        that.$message.success('上传成功！')
      }).catch(err => {
      })
    }
  }
}
</script>

<style scoped>
  .el-aside{
    line-height:80px;
    margin-left: 30px;
  }

  .text{
    font-size: 20px;
    font-weight: bold;
  }
</style>
